import uuid

import pymysql

from domain.User import User
from publicHandle.publicHandle import conn, cur, returnData


# 判断用户是否已经注册
def userJudge(account):
    connection = conn()
    cursor = cur(connection)
    mysql = "select account from user where account = %s"
    try:
        cursor.execute(mysql, (account))
        data = cursor.fetchone()
        if data == None:
            return False
        else:
            return True
    except:
        connection.rollback()
        return True
    finally:
        connection.commit()
        connection.close()
        cursor.close()


# 用户登录
def userLogin(account, password):
    connection = conn()
    cursor = cur(connection)
    print(account)
    mysql = "select userId,userName,account,passWord from user where account = %s"
    try:
        cursor.execute(mysql, (account))
        data = cursor.fetchone()
        if data != None:
            if (str(data[3] == str(password))):
                user = User(str(data[0]), str(data[1]), str(data[2]), str(data[3]))

                return returnData(user.JSONStr())
            else:
                return returnData({}, "密码错误", 400)
        else:
            return returnData({}, "用户名不存在", 400)
    except:
        connection.rollback()
        return returnData({}, "数据库访问失败", 400)
    finally:
        connection.commit()
        connection.close()
        cursor.close()


# 用户注册
def userRegister(userName, account, password):
    if userJudge(userName) == False:
        connection = conn()
        cursor = cur(connection)
        userId = uuid.uuid1().hex
        mysql = "insert into user(userId,userName,account,password) values (%s,%s,%s,%s)"
        try:
            cursor.execute(mysql, (userId, userName, account, password))
            return returnData(userName)
        except pymysql.Error as e:
            connection.rollback()
            return returnData({}, "访问数据库失败", 400)
        finally:
            connection.commit()
            connection.close()
            cursor.close()
    else:
        return returnData({}, "用户已存在", 400)
